<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch,onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import { addFirmwareApi } from "@/api/products/firmware";
import { getProductOptionsApi } from "@/api/products/product";
import { getStorageLocationOptions } from "@/utils/appCommon/appCommonOptions/products";
import UploadFile from "@/views/components/uploads/uploadFile.vue";
import UploadImg from "@/views/components/uploads/uploadImg.vue";
const { t } = useI18n();

// 定义props
const props = withDefaults(defineProps<{
  visible: boolean;
}>(), {
  visible: false
});

// 添加本地对话框状态
const dialogVisible = ref(props.visible);

// 监听prop变化同步到本地状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  },
  { immediate: true }
);

// 监听本地状态变化通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'success'): void;
}>();

// 表单数据 - 修改为小驼峰命名
const formData = ref<{
  name: string,
  productId: number,
  version: string,
  part: string,
  remark: string,
  fileMd5: string,
  fileUrl: string,
  whereAt: number,
  appFileId: number | null,
  image: string
}>({
  name: '',
  productId: 0,
  version: '',
  part: '',
  remark: '',
  fileMd5: '',
  fileUrl: '',
  whereAt: 0,
  appFileId: null,
  image: ''
});

// 产品选项
const productOptions = ref([]);

// 页面加载时获取产品选项
onMounted(async () => {
  const response = await getProductOptionsApi();
  if (response.code === 0) {
    productOptions.value = response.data.options;
  }
});

// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    if (!formData.value.name) { ElMessage.error(t('products.firmwarePage.pleaseEnterFirmwareName')); return; }
    if (!formData.value.version) { ElMessage.error(t('products.firmwarePage.pleaseEnterFirmwareVersion')); return; }
    if (!formData.value.productId) { ElMessage.error(t('products.firmwarePage.pleaseSelectProduct')); return; }

    const response = await addFirmwareApi(formData.value);
    if (response.code === 0) {
      ElMessage.success(t('products.firmwarePage.addFirmwareSuccess'));
      emit('update:visible', false);
      emit('success');
      resetForm();
    } else {
      ElMessage.error(response.msg || t('products.firmwarePage.addFirmwareFail'));
    }
  } catch (error) {
    ElMessage.error(t('products.firmwarePage.addFirmwareFail'));
    console.error('Failed to add firmware:', error);
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    productId: 0,
    version: '',
    part: '',
    remark: '',
    fileMd5: '',
    fileUrl: '',
    whereAt: 0,
    appFileId: null,
    image: ''
  };
};

// 关闭弹框
const closeDialog = () => {
  emit('update:visible', false);
  emit('close');
};

let storageLocationOptions = ref([])
onMounted(async () => {
  storageLocationOptions = await getStorageLocationOptions()
})

const handleFiremwareChange = (e:any)=> {
  console.log(e)
  formData.value.fileUrl = e
}

const handleImgChange = (e:any)=> {
  console.log(e)
  formData.value.image = e
}

</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('products.firmwarePage.addFirmware')"
    :draggable="true"
    @close="closeDialog"
  >
    <el-form
      :model="formData"
      style="max-width: 600px; margin: 0 auto;"
    >
      <el-form-item :label="t('products.firmwarePage.firmwareName')" prop="name" required>
        <el-input v-model="formData.name" :placeholder="t('products.firmwarePage.pleaseEnterFirmwareName')" />
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.productName')" prop="productId" required>
        <el-select v-model="formData.productId" :placeholder="t('products.firmwarePage.pleaseSelectProduct')">
          <el-option
            v-for="option in productOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.firmwareVersion')" prop="version" required>
        <el-input v-model="formData.version" :placeholder="t('products.firmwarePage.pleaseEnterFirmwareVersion')" />
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.firmwarePart')" prop="part">
        <el-input v-model="formData.part" :placeholder="t('products.firmwarePage.pleaseEnterFirmwarePart')" />
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.storageLocation')" prop="where_at">
        <el-select v-model="formData.whereAt" :placeholder="t('products.firmwarePage.storageLocation')">
          <el-option
            v-for="option in storageLocationOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.fileMd5')" prop="fileMd5">
        <el-input v-model="formData.fileMd5" :placeholder="t('products.firmwarePage.pleaseEnterFileMd5')" />
      </el-form-item>

      <el-form-item :label="t('products.firmwarePage.firmware')" prop="fileUrl" required>
        <upload-file v-model:filePath="formData.fileUrl" @change="handleFiremwareChange" />
        <div class="upload-hint">{{ t('products.firmwarePage.firmwareSourceLegal') }}</div>
      </el-form-item>

      <el-form-item :label="t('products.firmwarePage.appFileId')" prop="appFileId">
        <el-input v-model.number="formData.appFileId" :placeholder="t('products.firmwarePage.pleaseEnterAppFileId')" type="number" />
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.firmwareDescription')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('products.firmwarePage.pleaseEnterFirmwareDescription')"
        />
      </el-form-item>
      <el-form-item :label="t('products.firmwarePage.image')" prop="image" required>
        <upload-img v-model:imgUrl="formData.image" @change="handleImgChange" />
        <div class="upload-hint">{{ t('products.firmwarePage.imageFormatSupport') }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{ t('buttons.reset') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t('buttons.submit') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
// 可以添加一些自定义样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
